@echo off
setlocal enabledelayedexpansion
chcp 65001 > nul

rem ===== 设置工作目录 =====
cd /d "%~dp0"

rem ===== 创建日志目录 =====
if not exist "Logs" mkdir "Logs"
set "LOG_FILE=Logs\service-%date:~0,4%%date:~5,2%%date:~8,2%-%time:~0,2%%time:~3,2%.log"

rem ===== 环境变量配置 =====
set JASYPT_OPTION=
if not defined JASYPT_SECRET (
    echo [WARN] 环境变量 JASYPT_SECRET 未设置，将使用默认或配置文件中的密钥 >> "%LOG_FILE%"
) else (
    set JASYPT_OPTION=-Djasypt.encryptor.password="!JASYPT_SECRET!"
    echo [INFO] 使用环境变量中的Jasypt密钥 >> "%LOG_FILE%"
)

rem ===== 自动设置JAVA_HOME ====
if not defined JAVA_HOME (
    if exist "C:\Program Files\Eclipse Adoptium\jdk-17.0.14.7-hotspot\bin\java.exe" (
        set "JAVA_HOME=C:\Program Files\Eclipse Adoptium\jdk-17.0.14.7-hotspot"
    ) else if exist "C:\Program Files\Java\jdk-17\bin\java.exe" (
        set "JAVA_HOME=C:\Program Files\Java\jdk-17"
    ) else (
        where java >nul 2>&1
        if !errorlevel! equ 0 (
            for /f "delims=" %%i in ('where java') do set "JAVA_EXE=%%i"
            set "JAVA_HOME=!JAVA_EXE:\bin\java=!"
        )
    )
)

if not defined JAVA_HOME (
    echo [ERROR] JAVA_HOME未设置! 请确保已安装Java运行时 >> "%LOG_FILE%"
    exit /b 1
) else (
    echo [INFO] 使用JAVA_HOME: !JAVA_HOME! >> "%LOG_FILE%"
    set "PATH=!JAVA_HOME!\bin;!PATH!"
)

rem ===== 配置文件检查 =====
set OVERRIDE_OPTION=
if exist "config\override.yml" (
    set OVERRIDE_OPTION=--spring.config.additional-location=file:./config/override.yml
    echo [INFO] 检测到外部覆盖配置: config\override.yml >> "%LOG_FILE%"
) else (
    echo [WARN] 未找到外部覆盖配置，将使用JAR内默认配置 >> "%LOG_FILE%"
)

rem ===== 加载外部依赖库 =====
set LOADER_OPTION=-Dloader.path=./lib
echo [INFO] 添加lib目录依赖: .\lib >> "%LOG_FILE%"

rem ===== 核心启动命令 =====
echo [INFO] 正在启动应用... >> "%LOG_FILE%"
echo 启动时间: %date% %time% >> "%LOG_FILE%"

java ^
  -Dfile.encoding=UTF-8 ^
  !JASYPT_OPTION! ^
  !LOADER_OPTION! ^
  -jar ejp-app-1.0.0.jar ^
  !OVERRIDE_OPTION! ^
  --spring.config.import=optional:file:./config/application-common.yml >> "%LOG_FILE%" 2>&1

rem ===== 启动结果检查 =====
if %errorlevel% equ 0 (
    echo [SUCCESS] 应用启动成功! >> "%LOG_FILE%"
) else (
    echo [ERROR] 应用启动失败，错误码: %errorlevel% >> "%LOG_FILE%"
)

endlocal